package com.yc154.springmvc.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yc.starter.login.LoginProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    LoginProperties loginProperties;

    // 返回值 true 表示 , 允许访问目标资源
    // Object handler 控制器对象
    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {
        System.out.println("handler = " + handler);
        HttpSession session = request.getSession();
        // 判断会话中是否有登录的用户信息
        Object myinfo = session.getAttribute(loginProperties.getSessionKey());
        if (myinfo == null) {
            // 未登录
            // 根据当前的请求类型定义响应结果
            // 如果是表单请求 => 调整页面, 如果是 ajax 请求, 返回json
            String accpet = request.getHeader("Accept");
            if(accpet.contains("json")){
                // ajax请求
                response.setContentType("application/json;charset=utf-8");
                Map res = Map.of("code", 0, "msg", "请先登录系统");
                String json = new ObjectMapper().writeValueAsString(res);
                response.getWriter().write(json);
            } else {
                // 表单请求: 跳转页面
                response.sendRedirect("/msg.html");
            }
            return false;
        }
        return true;
    }
}
